<template>
  <div class="model-training">
    <div class="page-header">
      <h1>模型训练</h1>
    </div>
    
    <el-card shadow="hover" class="mb-4">
      <template #header>
        <div class="card-header">
          <span>训练配置</span>
        </div>
      </template>
      
      <el-form :model="trainingForm" label-width="120px" :rules="formRules" ref="trainingFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模型名称" prop="name">
              <el-input v-model="trainingForm.name" placeholder="请输入模型名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="模型类型" prop="model_type">
              <el-select v-model="trainingForm.model_type" placeholder="请选择模型类型" style="width: 100%" :loading="loadingModelTypes">
                <el-option 
                  v-for="item in modelTypeOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="模型描述">
              <el-input 
                v-model="trainingForm.description" 
                type="textarea" 
                placeholder="请输入模型描述（可选）" 
                :rows="3" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="startTraining" :loading="isTraining" :disabled="isTraining">开始训练</el-button>
          <el-button @click="resetForm" :disabled="isTraining">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card shadow="hover" v-if="isTraining || currentJob">
      <template #header>
        <div class="card-header">
          <span>训练状态</span>
          <el-tag v-if="currentJob" :type="getStatusTagType(currentJob.status)">{{ currentJob.status_display || currentJob.status }}</el-tag>
        </div>
      </template>
      
      <div v-if="isTraining || currentJob">
        <el-progress 
          :percentage="trainingProgress" 
          :status="trainingProgress < 100 ? '' : 'success'" 
          :indeterminate="currentJob && currentJob.status === 'running'"
        />
        
        <el-descriptions v-if="currentJob" title="训练作业信息" :column="3" border>
          <el-descriptions-item label="作业ID">{{ currentJob.job_id }}</el-descriptions-item>
          <el-descriptions-item label="模型名称">{{ currentJob.model_name }}</el-descriptions-item>
          <el-descriptions-item label="模型类型">{{ currentJob.model_type_display }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentJob.start_time_formatted || '未开始' }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentJob.end_time_formatted || '未结束' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ currentJob.status_display }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="training-logs mt-4">
          <h3>训练日志</h3>
          <pre v-if="currentJob && currentJob.log">{{ currentJob.log }}</pre>
          <p v-else class="no-logs">暂无日志信息...</p>
        </div>
        
        <div class="result-actions mt-4" v-if="currentJob && currentJob.status === 'completed'">
          <el-button type="success" @click="goToModel(modelId)">查看模型详情</el-button>
          <el-button type="primary" @click="activateModel">激活模型</el-button>
          <el-button @click="resetJob">返回</el-button>
        </div>

        <div class="result-actions mt-4" v-if="currentJob && currentJob.status === 'running'">
          <el-button type="danger" @click="cancelTraining">取消训练</el-button>
        </div>

        <div class="result-actions mt-4" v-if="currentJob && currentJob.status === 'failed'">
          <el-button @click="resetJob">返回</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="ModelTraining">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getModelTypes, 
  trainModel, 
  getModelTrainingJobDetail,
  activateModel as activateModelApi,
  cancelModelTrainingJob
} from '@/api/modules/models'

const router = useRouter()

// 表单引用
const trainingFormRef = ref(null)

// 模型类型选项
const modelTypeOptions = ref([])
const loadingModelTypes = ref(false)

// 训练表单 - 简化版
const trainingForm = reactive({
  name: '',
  description: '',
  model_type: 'RandomForest'
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ]
}

// 训练状态
const isTraining = ref(false)
const trainingProgress = ref(0)
const currentJob = ref(null)
const modelId = ref(null)
const jobId = ref(null)
const pollingInterval = ref(null)

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger',
    'cancelled': 'danger'
  }
  return types[status] || 'info'
}

// 生命周期钩子
onMounted(async () => {
  await fetchModelTypes()
})

// 获取模型类型
const fetchModelTypes = async () => {
  loadingModelTypes.value = true
  try {
    const res = await getModelTypes()
    modelTypeOptions.value = res
  } catch (error) {
    console.error('获取模型类型失败', error)
    ElMessage.error('获取模型类型失败')
  } finally {
    loadingModelTypes.value = false
  }
}

// 开始训练 - 简化版
const startTraining = async () => {
  if (trainingFormRef.value) {
    await trainingFormRef.value.validate(async (valid) => {
      if (!valid) {
        return false
      }
      
      try {
        isTraining.value = true
        trainingProgress.value = 0
        
        // 发送简化的训练请求，只包含必要的参数
        const res = await trainModel({
          name: trainingForm.name,
          description: trainingForm.description || '',
          model_type: trainingForm.model_type,
          hyperparameters: {},
          use_smote: true,
          use_feature_selection: true,
          test_size: 0.2
        })
        
        if (res.success) {
          ElMessage.success('模型训练任务已提交')
          modelId.value = res.model_id
          jobId.value = res.job_id
          
          // 轮询训练状态
          pollTrainingStatus()
        } else {
          ElMessage.error(res.error || '训练任务提交失败')
          isTraining.value = false
        }
      } catch (error) {
        console.error('提交训练任务失败', error)
        ElMessage.error('提交训练任务失败')
        isTraining.value = false
      }
    })
  }
}

// 轮询训练状态
const pollTrainingStatus = async () => {
  if (!jobId.value) return
  
  // 清除旧的轮询
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value)
  }
  
  // 立即获取一次作业状态
  await getJobStatus()
  
  // 设置轮询
  pollingInterval.value = setInterval(async () => {
    await getJobStatus()
    
    // 如果作业已完成或失败，停止轮询
    if (currentJob.value && ['completed', 'failed', 'cancelled'].includes(currentJob.value.status)) {
      clearInterval(pollingInterval.value)
      
      // 训练完成时设置进度为100%
      if (currentJob.value.status === 'completed') {
        trainingProgress.value = 100
      }
    }
  }, 3000)
}

// 获取作业状态
const getJobStatus = async () => {
  try {
    const res = await getModelTrainingJobDetail(jobId.value)
    currentJob.value = res
    
    // 根据作业状态更新进度
    switch(res.status) {
      case 'pending':
        trainingProgress.value = 5
        break
      case 'running':
        trainingProgress.value = 50
        break
      case 'completed':
        trainingProgress.value = 100
        isTraining.value = false
        break
      case 'failed':
      case 'cancelled':
        isTraining.value = false
        break
    }
  } catch (error) {
    console.error('获取作业状态失败', error)
  }
}

// 取消训练
const cancelTraining = async () => {
  try {
    // 这里应该调用取消训练的API
    ElMessageBox.confirm('确定要取消此训练任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await cancelModelTrainingJob(jobId.value)
      ElMessage.success('训练任务已取消')
    }).catch(() => {})
  } catch (error) {
    console.error('取消训练失败', error)
    ElMessage.error('取消训练失败')
  }
}

// 激活模型
const activateModel = async () => {
  if (!modelId.value) return
  
  try {
    await activateModelApi(modelId.value)
    ElMessage.success('模型已激活')
  } catch (error) {
    console.error('激活模型失败', error)
    ElMessage.error('激活模型失败')
  }
}

// 查看模型详情
const goToModel = (id) => {
  router.push(`/dashboard/models/${id}`)
}

// 重置表单 - 简化版
const resetForm = () => {
  if (trainingFormRef.value) {
    trainingFormRef.value.resetFields()
  }
  trainingForm.name = ''
  trainingForm.description = ''
  trainingForm.model_type = 'RandomForest'
}

// 重置作业状态
const resetJob = () => {
  currentJob.value = null
  modelId.value = null
  jobId.value = null
  isTraining.value = false
  trainingProgress.value = 0
  
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value)
    pollingInterval.value = null
  }
}
</script>

<style lang="scss" scoped>
.model-training {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 22px;
      font-weight: 500;
      margin: 0;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .mb-4 {
    margin-bottom: 20px;
  }
  
  .mt-4 {
    margin-top: 20px;
  }
  
  .training-logs {
    max-height: 300px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    margin-top: 15px;
    
    h3 {
      margin-top: 0;
    }
    
    pre {
      margin: 5px 0;
      font-family: monospace;
      font-size: 14px;
      white-space: pre-wrap;
      word-wrap: break-word;
      overflow-x: auto;
    }
    
    .no-logs {
      color: #909399;
      font-style: italic;
    }
  }
  
  .result-actions {
    display: flex;
    gap: 10px;
  }
}
</style> 